<?php
namespace app\index\controller;

use think\Db;
use think\Request;

class Index extends Common
{
    public function index()
    {
        return '<style type="text/css">*{ padding: 0; margin: 0; } .think_default_text{ padding: 4px 48px;} a{color:#2E5CD5;cursor: pointer;text-decoration: none} a:hover{text-decoration:underline; } body{ background: #fff; font-family: "Century Gothic","Microsoft yahei"; color: #333;font-size:18px} h1{ font-size: 100px; font-weight: normal; margin-bottom: 12px; } p{ line-height: 1.6em; font-size: 42px }</style><div style="padding: 24px 48px;"> <h1>:)</h1><p> ThinkPHP V5<br/><span style="font-size:30px">十年磨一剑 - 为API开发设计的高性能框架</span></p><span style="font-size:22px;">[ V5.0 版本由 <a href="http://www.qiniu.com" target="qiniu">七牛云</a> 独家赞助发布 ]</span></div><script type="text/javascript" src="https://tajs.qq.com/stats?sId=9347272" charset="UTF-8"></script><script type="text/javascript" src="https://e.topthink.com/Public/static/client.js"></script><think id="ad_bd568ce7058a1091"></think>';
    }


    /**
     *
     * 业绩统计
     * @return \think\response\Json
     */
    public function performanceCount(){
        $user_id = Request::instance()->param('user_id','','trim');

        if(!$user_id){
            return $this->error_msg('参数错误');
        }

        # 获取所有下级
        $users = $this->getLowerLevelUsers($user_id);
        $users = json_decode($users,true);

        $perfData = [];
        # 人员业绩

        $staffPerf = $this->staffCount($users);
        $staffPerf = json_decode($staffPerf,true);
        if($staffPerf['status'] == 'success'){
            $staffPerf = $staffPerf['message'];
            $perfData = array_merge($perfData,$staffPerf);
        }

        # 企业需求业绩
        $demandPerf = $this->demandCount($users);
        $demandPerf = json_decode($demandPerf,true);
        if($demandPerf['status'] == 'success'){
            $demandPerf = $demandPerf['message'];
            $perfData = array_merge($perfData,$demandPerf);
        }
        # 收资质业绩
        $qualityInPerf = $this->qualityInCount($users);
        $qualityInPerf = json_decode($qualityInPerf,true);
        if($qualityInPerf['status'] == 'success'){
            $qualityInPerf = $qualityInPerf['message'];
            $perfData = array_merge($perfData,$qualityInPerf);
        }
        # 出资质业绩
        $qualityOutPerf = $this->qualityOutCount($users);
        $qualityOutPerf = json_decode($qualityOutPerf,true);
        if($qualityOutPerf['status'] == 'success'){
            $qualityOutPerf = $qualityOutPerf['message'];
            $perfData = array_merge($perfData,$qualityOutPerf);
        }

//        dump($staffPerf);
        $perfData = $this->dealPerfDataType($perfData);
        $perfData = json_decode($perfData,true);
        if($perfData['status'] == 'success'){
            $perfData = $perfData['message'];

        }else{
            return $this->error_msg($perfData['message']);
        }

        if($perfData){
            return $this->success_msg($perfData);
        }else{
            return $this->success_msg(3);
        }

    }

    public function calcStaff(){
        $user_id = Request::instance()->param('user_id','9c30dc2ab9bbc3f1e0d128366c9178d3','trim');
        if(!$user_id){
            return $this->error_msg('参数错误');
        }

        # 获取所有下级
        $users = $this->getLowerLevelUsers($user_id);
        $users = json_decode($users,true);

        # 人员
        $staffCount = $this->staffCount($users);
        $staffCount = json_decode($staffCount,true);
        if($staffCount['status'] == 'success'){
            $staffCount = $staffCount['message'];
        }
        # 企业需求
        $demandPerf = $this->demandCount($users);
        $demandPerf = json_decode($demandPerf,true);
        if($demandPerf['status'] == 'success'){
            $demandPerf = $demandPerf['message'];
            $staffCount = array_merge($staffCount,$demandPerf);
        }


        $staffPerf = $this->dealPerfDataType($staffCount);
        $staffPerf = json_decode($staffPerf,true);
        if($staffPerf['status'] == 'success'){
            $staffPerf = $staffPerf['message'];
        }
        $nowYear = Date('Y',time());
        $nowMonth = Date('n',time());


        # 统计一年业绩
        if(isset($staffPerf[$nowYear])){
            $yearCount = array_sum($staffPerf[$nowYear]);

            #获取当前月的业绩 和上一个月业绩
            $nowMonthPerf = isset($staffPerf[$nowYear][$nowMonth])?$staffPerf[$nowYear][$nowMonth]:0;
            if($nowMonthPerf != 1){
                $beforeMonth = $nowMonth-1; # 如果当前是1月份,则不计算业绩增长率
                $beforeMonthPerf = isset($staffPerf[$nowYear][$nowMonth])?$staffPerf[$nowYear][$beforeMonth]:0;
            }else{
                $beforeMonthPerf = 0;
            }


            if(isset($staffPerf[$nowYear][$nowMonth])){
                $nowMonthPerf = $staffPerf[$nowYear][$nowMonth];
                $monthCount = $nowMonthPerf;
                if($nowMonth != 1){ # 如果是1月份  则不需要计算业绩变化率
                    $beforeMonth = $nowMonth-1; # 如果当前是1月份,则不计算业绩增长率
                    if(isset($staffPerf[$nowYear][$beforeMonth])){
                        $beforeMonthPerf = $staffPerf[$nowYear][$beforeMonth];
                    }else{
                        $beforeMonthPerf = 0;
                    }

                    if($beforeMonthPerf){
                        if($nowMonthPerf>=$beforeMonthPerf){
                            $calc = round(($nowMonthPerf-$beforeMonthPerf)/$nowMonthPerf*100,2).'%';
                            $calcMonth = ['type'=>'up','result'=>$calc];
                        }else{
                            $calc = round(($beforeMonthPerf-$nowMonthPerf)/$beforeMonthPerf*100,2).'%';
                            $calcMonth = ['type'=>'down','result'=>$calc];
                        }
                    }else{
                        $calcMonth = ['type'=>'down','result'=>0];
                    }
                }else{
                    $calcMonth = ['type'=>'up','result'=>0];
                }
            }else{
                $monthCount = 0;
                $calcMonth = ['type'=>'up','result'=>0];
            }
            

        }else{
            $yearCount = 0;
            $monthCount = 0;
            $calcMonth = ['type'=>'up','result'=>0];
        }

        return $this->success_msg(['yearCount'=>$yearCount,'monthCount'=>$monthCount,'calcMonth'=>$calcMonth]);

    }

    /**
     * 人员业绩统计
     * @param $user_ids
     * @return mixed|string
     */
    private function staffCount($user_ids){
        $user_ids = is_array($user_ids)?$user_ids:[$user_ids];

        $where = [
            'staff.user_id'=> ['in',$user_ids],
            'staff_cards.status'=>['not in',['f95c1a880f5ad672ccf76516a620e811','6b5a6fee46bd69ff59114ebeaf739115']] # 潜在客户/未通过
        ];
        $result = Db::view('staff_cards','talent_price as price,modified')
            ->view('staff','user_id','staff.staff_id = staff_cards.staff_id','left')
            ->where($where)
            ->select();
        if($result){
            return json_encode(['status'=>'success','message'=>$result]);
        }else{
            return json_encode(['status'=>'failed','message'=>'暂无数据']);
        }

    }

    /**
     * 企业需求业绩统计
     * @param $user_ids
     * @return mixed|string
     */
    private function demandCount($user_ids){
        $user_ids = is_array($user_ids)?$user_ids:[$user_ids];

        $where = [
            'company_demand.user_id'=> ['in',$user_ids],
            'company_demand.customer_type'=>['not in',['f95c1a880f5ad672ccf76516a620e811','6b5a6fee46bd69ff59114ebeaf739115']] # 潜在客户/未通过
        ];
        $result = Db::view('demand_cards','company_price as price,modified')
            ->view('company_demand','user_id','company_demand.demand_id = demand_cards.demand_id','left')
            ->where($where)
            ->select();
        if($result){
            return json_encode(['status'=>'success','message'=>$result]);
        }else{
            return json_encode(['status'=>'failed','message'=>'暂无数据']);
        }

    }

    /**
     * 收资质业绩统计
     * @param $user_ids
     * @return mixed|string
     */
    private function qualityInCount($user_ids){
        $user_ids = is_array($user_ids)?$user_ids:[$user_ids];

        $where = [
            'quality.user_id'=> ['in',$user_ids],
            'quality_cards.status'=>['not in',['f95c1a880f5ad672ccf76516a620e811','6b5a6fee46bd69ff59114ebeaf739115']] # 潜在客户/未通过
        ];
        $result = Db::view('quality_cards','company_price as price,modified')
            ->view('quality','user_id','quality.quality_id = quality_cards.quality_id','left')
            ->where($where)
            ->select();
        if($result){
            return json_encode(['status'=>'success','message'=>$result]);
        }else{
            return json_encode(['status'=>'failed','message'=>'暂无数据']);
        }

    }

    /**
     * 出资质统计
     * @param $user_ids
     * @return mixed|string
     */
    private function qualityOutCount($user_ids){
        $user_ids = is_array($user_ids)?$user_ids:[$user_ids];

        $where = [
            'quality_demand.user_id'=> ['in',$user_ids],
            'quality_demand.customer_type'=>['not in',['f95c1a880f5ad672ccf76516a620e811','6b5a6fee46bd69ff59114ebeaf739115']] # 潜在客户/未通过
        ];
        $result = Db::view('quality_demand_card','customer_price as price,modified')
            ->view('quality_demand','user_id','quality_demand.quality_demand_id = quality_demand_card.quality_demand_id','left')
            ->where($where)
            ->select();
        if($result){
            return json_encode(['status'=>'success','message'=>$result]);
        }else{
            return json_encode(['status'=>'failed','message'=>'暂无数据']);
        }

    }


    /**
     *
     * 格式化业绩数据
     * @param $data
     * @return mixed|string
     */
    private function dealPerfDataType($data){
        if(!is_array($data)){
            return json_encode(['status'=>'failed','message'=>'参数错误']);
        }
        if($data){
            $final_data = [];
            $modified = min(array_column($data,'modified'));

//        dump($data);
//        dump($modified);
            $modified = strtotime($modified);

            $minYear = date('Y',$modified);
            $nowYear = date('Y',time());
            $minMonth = date('n',$modified);
            $nowMonth = date('n',$modified);

//        # 方案一  实际开始和结束年月
//        for($i=$minYear;$i<=$nowYear;$i++){
//
//            # 先判断是否等于今年  然后再判断是否等于开始起始时间
//            # **这样才能避免起始时间等于今年时,格式化数组的月份出错
//            if($i == $nowYear){
//                for($j=1;$j<=$nowMonth;$j++){
//                    $final_data[$i][$j] = 0;
//                }
//            }elseif($i == $minYear){
//                for($j = $minMonth;$j<=12;$j++){
//                    $final_data[$i][$j] = 0;
//                }
//            }else{
//                for($j=1;$j<=12;$j++){
//                    $final_data[$i][$j] = 0;
//                }
//            }
//        }

            # 方案二  给足每年的月份
            for($i=$minYear;$i<=$nowYear;$i++){
                for($j = 1;$j<=12;$j++){
                    $final_data[$i][$j] = 0;
                }
            }

            foreach ($data as $datum){
//            $year = substr($datum['modified'],0,4);
//            $month = substr($datum['modified'],1,2);

                $year = date('Y',strtotime($datum['modified']));
                $month = date('n',strtotime($datum['modified']));
                if(!isset($final_data[$year][$month])){
                    $final_data[$year][$month] = 0;
                }
                $final_data[$year][$month] += $datum['price'];
            }
        }else{
            $nowYear = date('Y',time());
            for($j = 1;$j<=12;$j++){
                $final_data[$nowYear][$j] = 0;
            }
        }


        return json_encode(['status'=>'success','message'=>$final_data]);

    }




    /**
     * 签约成功的轮播公告列表
     * @return \think\response\Json
     */
    public  function perfFigureList(){
        $sql = "( SELECT DISTINCT name, audio_time, user_id FROM staff INNER JOIN staff_cards ON staff.staff_id = staff_cards.staff_id WHERE staff_cards. STATUS = '6b5a6fee46bd69ff59114ebeaf739115' ORDER BY audio_time DESC LIMIT 10 ) UNION ( SELECT company_name AS name, audio_time, user_id FROM company_demand ORDER BY audio_time LIMIT 10 ) UNION ( SELECT DISTINCT customer_name as name, audio_time, user_id FROM quality INNER JOIN quality_cards ON quality.quality_id = quality_cards.quality_id WHERE quality_cards. STATUS = '6b5a6fee46bd69ff59114ebeaf739115' ORDER BY audio_time DESC LIMIT 10 ) UNION ( SELECT customer_name AS name, audio_time, user_id FROM quality_demand ORDER BY audio_time LIMIT 10 )";
        $result = Db::query($sql);
        $final_data = [];
        if($result){
            $user_list = array_column($result,'user_id');
            $userResult = Db('user')->field('user_id,user_name')->where(['user_id'=>['in',$user_list]])->select();
            $user_id_map = array_column($userResult,'user_name','user_id');
            $exists_user = array_column($userResult,'user_id');
            $data = [];
            foreach ($result as $value){
                if(in_array($value['user_id'],$exists_user)){
                    $temp = [
                        $value['name'],
                        $value['audio_time'],
                        $user_id_map[$value['user_id']]
                    ];
                    $data[] = $temp;
                }
            }

            $sort_list = [];

            if($data){

                foreach($data as $datum){
                    $sort_list[] = $datum[1];
                }
                array_multisort($sort_list,3,$data);

                $data = array_slice($data,0,10);
                foreach($data as $datum){
                    $str = '恭喜"'.$datum[2].'"签约"'.$datum[0].'"成功';
                    $final_data[] = $str;
                }
            }

            if($final_data){
                return $this->success_msg($final_data);
            }else{
                return $this->success_msg('3');
            }

        }else{
            return $this->success_msg('3');
        }


//        dump($result);

    }




    /**
     * 保存/修改公告
     * @return \think\response\Json
     */
    public function saveNotice(){
        $request = Request::instance();
        $user_id = $request->param('user_id','','trim');
        $title = $request->param('title','','trim');
        $content = $request->param('content','','trim');
        $id = $request->param('id','','trim');
        if(!$user_id){
            return $this->error_msg('参数错误');
        }
        if(!$title){
            return $this->error_msg('标题必填');
        }
        if(!$content){
            return $this->error_msg('内容必填');
        }

        if(!$id){
            $data = [
                'user_id'   =>  $user_id,
                'title'     =>  $title,
                'content'   =>  $content
            ];

            $result = Db('notice')->insert($data);
        }else{
            $data = [
                'title'     =>  $title,
                'content'   =>  $content
            ];
            $result = Db('notice')->where(['id'=>$id])->update($data);
        }

        if($result){
            return $this->success_msg(1);
        }else{
            return $this->error_msg(2);
        }

    }

    /**
     * 获取公告列表
     * @return \think\response\Json
     */
    public  function getNoticeList(){
        $page = Request::instance()->param('page',1,'intval');
        $rows = Request::instance()->param('rows',10,'intval');
        $begin_item = ($page-1)*$rows;
        $result = Db::view('notice','id,title,content,modified')
            ->view('user','user_name','user.user_id = notice.user_id','left')
            ->where(['notice.valid'=>1])
            ->order('notice.modified desc')
            ->limit($begin_item,$rows)
            ->select();
        $count = Db('notice')->where(['notice.valid'=>1])->count();
        if($result){
            return $this->success_msg($result,$count);
        }else{
            return $this->success_msg(3);
        }
    }

    /**
     * 获取公告详情
     * @return \think\response\Json
     */
    public function getNoticeDetail(){
        $id = Request::instance()->param('id',0,'intval');
        $result = Db('notice')->field('id,title,content,modified')->where(['id'=>$id,'valid'=>1])->select();
        if($result){
            return $this->success_msg($result);
        }else{
            return $this->error_msg('参数错误');
        }

    }

    /**
     * 删除公告
     * @return \think\response\Json
     */
    public function delNotice(){
        $id = Request::instance()->param('id',0,'intval');
        $data = ['valid'=>2];
        $result = Db('notice')->where(['id'=>$id])->update($data);
        if($result){
            return $this->success_msg($result);
        }else{
            return $this->error_msg('参数错误');
        }

    }


}
